package com.hdl.school.schoolcontroller;

import android.animation.ObjectAnimator;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSON;
import com.hdl.school.application.MyApplication;
import com.hdl.school.bean.PlanTask;
import com.hdl.school.utils.BroadcastAction;
import com.hdl.school.utils.StringUtil;
import com.hdl.school.utils.TimeUtil;
import com.hdl.school.view.IjkVideoView;
import com.leectrl.utils.Bus;

import org.videolan.libvlc.MediaPlayer;

public class VlcVideoActivity extends CardSlotActivity {

    private final static String TAG = "[VlcVideoActivity]";
    /**
     * 视频播放控制界面
     */
    private IjkVideoView mVideoView;
    private LinearLayout mLoadingLayout;
    private ImageView mLoadingImg;
    private ObjectAnimator mOjectAnimator;
    private TextView totalDur;
    private TextView currentPositionText;
    //视频总长度
    private long duration = 0;
    /**
     * 当前进度
     */
    private Long currentPosition = (long) 0;
    /**
     * setting
     */
    private boolean needResume;

    private MyReceiver myReceiver;

    private PlanTask planTask;
    private Thread positionDectionThread;
    private int errTime=0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.video_play_layout);
        myReceiver = new MyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(BroadcastAction.ACTION_MEDIA_ENVENT);
        registerReceiver(myReceiver, filter);
        Intent intent=getIntent();
        String task = intent.getStringExtra("task");
        planTask= JSON.parseObject(task,PlanTask.class);
        MyApplication.getAppContext().setMediaPlaying(true);
        initviews();
        initVideoSettings();
        startPlay();

    }


    private void initviews() {
        mVideoView = (IjkVideoView) findViewById(R.id.surface_view);
        mLoadingLayout = (LinearLayout) findViewById(R.id.loading_LinearLayout);
        mLoadingImg = (ImageView) findViewById(R.id.loading_image);
        totalDur=findViewById(R.id.totalDur);
        currentPositionText=findViewById(R.id.currentPosition);
    }

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if(mVideoView!=null){
                currentPosition=mVideoView.getCurrentPosition();
                if(currentPosition<=duration){
                    currentPositionText.setText(StringUtil.padNum(currentPosition / 3600000,2) + ":" + StringUtil.padNum((currentPosition - (currentPosition / 3600000) * 3600000) / 60000,2) + ":" + StringUtil.padNum((currentPosition%60000)/1000,2));
                }

            }
            if(handler!=null){
                handler.sendEmptyMessageDelayed(0,1000);
            }
        }
    };

    private void initVideoSettings() {
        mVideoView.requestFocus();
//        if (planTask.getFileUrl().startsWith("udp://")) {
//            mVideoView.setBufferSize(2 * 1024);
//        } else {
//            mVideoView.setBufferSize(10 * 1024);
//        }
//        mVideoView.setVideoChroma(MediaPlayer.VIDEOCHROMA_RGB565);
        mVideoView.setPath(planTask.getFileUrl());


    }

    public void onResume() {
        super.onResume();
        preparePlayVideo();
    }

    private void preparePlayVideo() {
        startLoadingAnimator();
        mVideoView.setListener(new MediaPlayer.EventListener() {
            @Override
            public void onEvent(MediaPlayer.Event event) {
                switch (event.type) {
                    case MediaPlayer.Event.Buffering:
                        if (event.getBuffering() == 1.0f) {
                            // Buffering start
                            startLoadingAnimator();
                            if (mVideoView.isPlaying()) {
                                stopPlay();
                                needResume = true;
                            }
                        } else if (event.getBuffering() == 0.0f) {
                            // Buffering end
                            stopLoadingAnimator();
                            if (needResume) {
                                startPlay();
                            }
                        }
                        break;
                    case MediaPlayer.Event.EndReached:
                        if (planTask.isLoop()) {
                            currentPositionText.setText("00:00:00");
                            // mediaPlayer.setMedia(new Media(libVLC, planTask.getFileUrl())); // reset media
                            mVideoView.start();
                        } else {
                            stopPlay();
                            finish();
                        }
                        break;
                    case MediaPlayer.Event.EncounteredError:
                        Log.e("mVideoView", "error");
                        errTime++;

//                        mVideoView.setMedia(new Media(libVLC, planTask.getFileUrl()));
                        if(errTime< 10){
                            mVideoView.setPath(planTask.getFileUrl());
                            startPlay();
                        }

                        break;
                    case MediaPlayer.Event.Playing:
                        stopLoadingAnimator();
                        handler.sendEmptyMessage(0);
                        mVideoView.setRepeat(planTask.isLoop());

                        if (!(planTask.getFileUrl().startsWith("udp://"))) {
                            Log.e("vlc", "now:" + TimeUtil.getCurTimeToString("HH:mm:ss") + ",start:" + TimeUtil.long2String(planTask.getTime(), "HH:mm:ss"));
                            long duration = mVideoView.getLength();
                            totalDur.setText(StringUtil.padNum(duration / 3600000, 2) + ":" + StringUtil.padNum((duration - (duration / 3600000) * 3600000) / 60000, 2) + ":" + StringUtil.padNum((duration % 60000) / 1000, 2));
                            Log.e("vlc", "视频时长:" + duration / 3600000 + "h" + (duration - (duration / 3600000) * 3600000) / 60000 + "m");
                            if (duration > 0) {
                                long currentPosition = (TimeUtil.currentStap() - planTask.getTime()) % duration;
                                Log.e("vlc", "视频进度:" + currentPosition / 3600000 + "h" + (currentPosition - (currentPosition / 3600000) * 3600000) / 60000 + "m");
                                mVideoView.setTime(currentPosition);
                            }
                        }
                        break;
                }
            }
        });
    }
    @NonNull
    private void startLoadingAnimator() {
        if (mOjectAnimator == null) {
            mOjectAnimator = ObjectAnimator.ofFloat(mLoadingImg, "rotation", 0f, 360f);
        }
        mLoadingLayout.setVisibility(View.VISIBLE);

        mOjectAnimator.setDuration(1000);
        mOjectAnimator.setRepeatCount(-1);
        mOjectAnimator.start();
    }

    private void stopLoadingAnimator() {
        mLoadingLayout.setVisibility(View.GONE);
        mOjectAnimator.cancel();
    }

    private void startPlay() {
        mVideoView.start();
        Bus.getInstance().emit("scene_event","video_start");
    }

    private void stopPlay() {
        mVideoView.pause();
        Bus.getInstance().emit("scene_event","video_finish");
    }

    public void onPause() {
        super.onPause();
        currentPosition = mVideoView.getCurrentPosition();
        mVideoView.pause();

    }


    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        Log.e("vlc", "结束播放");
        unregisterReceiver(myReceiver);
        MyApplication.getAppContext().setMediaPlaying(false);
        needResume=false;
        if (mVideoView != null) {
            mVideoView.release();
        }

        super.onDestroy();
    }



    /**
     * 快退(每次都快进视频总时长的1%)
     */
    public void speedVideo() {
        if (mVideoView != null) {
            long duration = mVideoView.getDuration();
            long currentPosition = mVideoView.getCurrentPosition();
            long goalduration = currentPosition + duration / 10;
            if (goalduration >= duration) {
                mVideoView.seekTo(duration);
            } else {
                mVideoView.seekTo(goalduration);
            }
        }
    }

    /**
     * 快退(每次都快退视频总时长的1%)
     */
    public void reverseVideo() {
        if (mVideoView != null) {
            long duration = mVideoView.getDuration();
            long currentPosition = mVideoView.getCurrentPosition();
            long goalduration = currentPosition - duration / 10;
            if (goalduration <= 0) {
                mVideoView.seekTo(0);
            } else {
                mVideoView.seekTo(goalduration);
            }

        }
    }

    /**
     * 设置屏幕的显示大小
     */
    public void setVideoPageSize(int currentPageSize) {
//        if (mVideoView != null) {
//            mVideoView.setVideoLayout(currentPageSize, 0);
//        }
    }



    class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            String mAction = intent.getStringExtra("action");
            Log.e("VlcVideoActivity", action + "=>" + mAction);
            if (BroadcastAction.ACTION_MEDIA_ENVENT.equals(action)) {
                if (mAction.equals("stopVideo") || mAction.equals("stopall")) {
                    finish();
                }
            }
        }
    }
}
